<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter title="赠送体验券" :width="drawerWidth" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { formSchema } from '../data/data';
import { addTiyanVipCard } from '../data/api';
import { useAppInject } from '@apps/antd-admin/src/hooks/web/use-app-inject';
const { getIsMobile } = useAppInject();
const drawerWidth = ref('650px');
if (unref(getIsMobile)) {
  drawerWidth.value = '80%';
}
// 声明Emits
const emit = defineEmits(['success', 'register']);
//是否是编辑模式
const isUpdate = ref(true);
//配置表单
const [registerForm, { resetFields, setProps, setFieldsValue, validate }] = useForm({
  labelWidth: 120,
  labelCol: {
    span: 4,
  },
  schemas: formSchema,
  showActionButtonGroup: false,
});
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  setDrawerProps({ confirmLoading: false });
  await resetFields();
  isUpdate.value = !!data?.isUpdate;
  if (isUpdate.value) {
    await setFieldsValue(data.record);
    setProps({ disabled: true });
  }
});

/**
 * 表单提交
 */
async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    await addTiyanVipCard(values);
    closeDrawer();
    emit('success', false);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
